package com.ledim.db;

import android.database.sqlite.SQLiteDatabase;
import com.ledim.app.LeDimApplication;
import com.ledim.db.dao.DaoMaster;
import com.ledim.db.dao.DaoSession;

/**
 * Created by ccx on 16/11/2.
 * GreenDao管理类
 */

public class LedimDBManager {

    private final static String dbName = "letv.db";
    private static LedimDBManager mInstance;
    private static DaoMaster.DevOpenHelper mDevOpenHelper;
    private static DaoMaster mDaoMaster;
    private static DaoSession mDaoSession;

    private LedimDBManager() {
        mDevOpenHelper = new DaoMaster.DevOpenHelper(LeDimApplication.getInstance()
                                                                     .getApplicationContext(), dbName, null);
    }

    public static LedimDBManager getInstance() {
        if (mInstance == null) {
            synchronized (LedimDBManager.class) {
                if (mInstance == null) {
                    mInstance = new LedimDBManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * @desc 获取可读数据库
     **/
    public static SQLiteDatabase getReadableDatabase() {
        if (null == mDevOpenHelper) {
            getInstance();
        }
        return mDevOpenHelper.getReadableDatabase();
    }

    /**
     * @desc 获取可写数据库
     **/
    public static SQLiteDatabase getWritableDatabase() {
        if (null == mDevOpenHelper) {
            getInstance();
        }
        return mDevOpenHelper.getWritableDatabase();
    }

    /**
     * @desc 获取DaoMaster
     **/
    public static DaoMaster getDaoMaster() {
        if (null == mDaoMaster) {
            synchronized (LedimDBManager.class) {
                if (null == mDaoMaster) {
                    mDaoMaster = new DaoMaster(getWritableDatabase());
                }
            }
        }
        return mDaoMaster;
    }

    /**
     * @desc 获取DaoSession
     **/
    public static DaoSession getDaoSession() {
        if (null == mDaoSession) {
            synchronized (LedimDBManager.class) {
                mDaoSession = getDaoMaster().newSession();
            }
        }

        return mDaoSession;
    }

}
